﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PojProject.Models;

namespace PojProject.Pojs
{
    public class Poj1328
    {
        List<Point> islandLocations;
        double radRadius;
        List<KeyValuePair<double, double>> RangesOfIsland;
        List<double> result;

        public Poj1328(List<Point> isLandLocations, double radRadius)
        {
            this.islandLocations = isLandLocations;
            this.radRadius = radRadius;

            RangesOfIsland = GetRangeOfIsland();
        }


        // And must be order by 
        private List<KeyValuePair<double, double>> GetRangeOfIsland()
        {
            List<KeyValuePair<double, double>> ls = new List<KeyValuePair<double, double>>();

            foreach (var island in islandLocations)
            {
                var v1 = Math.Sqrt(radRadius * radRadius - island.Y * island.Y);

                ls.Add(new KeyValuePair<double, double>(island.X - v1, island.X + v1));
            }

            return ls.OrderBy(x => x.Key).ToList();
        }

        public bool IsInRange(double tagetValue, KeyValuePair<double, double> range)
        {
            if (tagetValue >= range.Key && tagetValue <= range.Value)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private List<KeyValuePair<double, double>> MergeRange()
        {
            List<KeyValuePair<double, double>> mergeRange = new List<KeyValuePair<double, double>>();

            foreach (var item in RangesOfIsland)
            {
                if (mergeRange.Count == 0)
                {
                    mergeRange.Add(item);
                }
                else
                {
                    var v = mergeRange.FirstOrDefault(x => IsInRange(item.Key, x) || IsInRange(item.Value, x));

                    if (!v.Equals(null))
                    {
                         mergeRange.Remove(v);
                        if (item.Key > v.Key)
                        {
                           
                            mergeRange.Add(new KeyValuePair<double, double>(item.Key, v.Value));
                        }
                        else
                        {
                            mergeRange.Add(new KeyValuePair<double, double>(v.Key, item.Value));
                        }
                    }
                    else
                    {
                        mergeRange.Add(item);
                    }
                }
            }

            return mergeRange;
        }

        public List<KeyValuePair<double, double>> Play()
        {
            return MergeRange();
        }
    }
}
